import xml.etree.ElementTree as ET
from datetime import datetime
import pytz

def create_rss_feed(articles: list, output_path: str, feed_config: dict):
    """
    根据文章列表创建一个RSS文件，使用自定义命名空间分开文章信息。

    Args:
        articles: 包含筛选后文章的字典列表。
        output_path: 生成的RSS文件的保存路径。
        feed_config: 包含RSS feed元数据（如标题、链接、描述）的字典。
    """
    # 创建RSS根元素
    rss = ET.Element('rss', {
        'version': '2.0',
        'xmlns:atom': 'http://www.w3.org/2005/Atom',
        'xmlns:content': 'http://purl.org/rss/1.0/modules/content/',
        'xmlns:article': 'http://example.com/article'
    })
    
    # 创建channel
    channel = ET.SubElement(rss, 'channel')
    
    # 添加channel信息
    ET.SubElement(channel, 'title').text = feed_config.get('title', 'Personalized AI RSS Feed')
    ET.SubElement(channel, 'link').text = feed_config.get('link', 'http://localhost')
    ET.SubElement(channel, 'description').text = feed_config.get('description', 'Articles filtered by AI based on my interests.')
    ET.SubElement(channel, 'docs').text = 'http://www.rssboard.org/rss-specification'
    ET.SubElement(channel, 'generator').text = 'smart-rss-service'
    ET.SubElement(channel, 'language').text = 'zh-CN'
    ET.SubElement(channel, 'lastBuildDate').text = datetime.now(pytz.UTC).strftime('%a, %d %b %Y %H:%M:%S +0000')
    
    # 添加文章条目
    for article in articles:
        item = ET.SubElement(channel, 'item')
        
        title = article['title']
        reason = article.get('selection_reason')
        # 如果文章是因优先关注而被选中，则在标题前添加标记
        if reason and reason != 'interest':
            title = f"[{reason}] {title}"
        
        ET.SubElement(item, 'title').text = title
        ET.SubElement(item, 'link').text = article['link']
        
        # 解析文章摘要信息
        if 'summary' in article and article['summary']:
            summary_lines = article['summary'].split('\n\n')
            
            # 使用自定义标签分开文章信息
            for line in summary_lines:
                if line.startswith('期刊:'):
                    ET.SubElement(item, 'article:journal').text = line[3:].strip()
                elif line.startswith('作者:'):
                    ET.SubElement(item, 'article:authors').text = line[3:].strip()
                elif line.startswith('DOI:'):
                    ET.SubElement(item, 'article:doi').text = line[4:].strip()
                elif line.startswith('摘要:'):
                    ET.SubElement(item, 'article:abstract').text = line[3:].strip()
            
            # 为Outlook等RSS阅读器创建完整的描述内容，使用HTML格式
            description_parts = []
            # 第一行添加标题
            description_parts.append(f"<strong>标题:</strong> {title}")
            
            # 添加中文翻译（如果存在）
            if article.get('title_zh') and article.get('summary_zh'):
                description_parts.append(f"<strong>中文标题:</strong> {article['title_zh']}")
                description_parts.append(f"<strong>中文摘要:</strong> {article['summary_zh']}")
                description_parts.append("<hr>")
            
            for line in summary_lines:
                if line.startswith('期刊:'):
                    description_parts.append(f"<strong>期刊:</strong> {line[3:].strip()}")
                elif line.startswith('作者:'):
                    description_parts.append(f"<strong>作者:</strong> {line[3:].strip()}")
                elif line.startswith('DOI:'):
                    description_parts.append(f"<strong>DOI:</strong> {line[4:].strip()}")
                elif line.startswith('摘要:'):
                    description_parts.append(f"<strong>摘要:</strong> {line[3:].strip()}")
                else:
                    description_parts.append(line)
            
            # 使用HTML格式确保在Outlook中正确显示换行
            html_description = '<br><br>'.join(description_parts)
            ET.SubElement(item, 'description').text = html_description
        else:
            ET.SubElement(item, 'description').text = article.get('summary', '')
        
        # 处理发布日期
        if article['published']:
            pub_date = datetime(*article['published'][:6], tzinfo=pytz.UTC)
            ET.SubElement(item, 'pubDate').text = pub_date.strftime('%a, %d %b %Y %H:%M:%S +0000')
    
    # 写入文件
    tree = ET.ElementTree(rss)
    
    # 添加缩进让XML更易读
    def indent(elem, level=0):
        i = "\n" + level * "  "
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "  "
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for elem in elem:
                indent(elem, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i
    
    indent(rss)
    tree.write(output_path, encoding='utf-8', xml_declaration=True)